package com.ljs.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.ljs.springbootinit.annotation.AuthCheck;
import com.ljs.springbootinit.bizMq.BiMessageProducer;
import com.ljs.springbootinit.common.BaseResponse;
import com.ljs.springbootinit.common.DeleteRequest;
import com.ljs.springbootinit.common.ErrorCode;
import com.ljs.springbootinit.common.ResultUtils;
import com.ljs.springbootinit.constant.CommonConstant;
import com.ljs.springbootinit.constant.UserConstant;
import com.ljs.springbootinit.exception.BusinessException;
import com.ljs.springbootinit.exception.ThrowUtils;
import com.ljs.springbootinit.manager.AiManage;
import com.ljs.springbootinit.manager.RedisLimitManage;
import com.ljs.springbootinit.model.dto.chart.*;
import com.ljs.springbootinit.model.entity.Chart;
import com.ljs.springbootinit.model.entity.User;
import com.ljs.springbootinit.model.vo.AiResponse;
import com.ljs.springbootinit.service.ChartService;
import com.ljs.springbootinit.service.UserService;
import com.ljs.springbootinit.utils.ExcelUtils;
import com.ljs.springbootinit.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    private final static Gson GSON = new Gson();
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private RedisLimitManage redisLimitManage;
    @Resource
    private AiManage aiManage;
    @Resource
    private ChartService ChartService;
    @Resource
    private UserService userService;
    @Resource
    private BiMessageProducer biMessageProducer;
    // region 增删改查

    /**
     * 创建
     *
     * @param ChartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest ChartAddRequest, HttpServletRequest request) {
        if (ChartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(ChartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = ChartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = ChartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param ChartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest ChartUpdateRequest) {
        if (ChartUpdateRequest == null || ChartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(ChartUpdateRequest, chart);
        long id = ChartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = ChartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = ChartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     * @param ChartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest ChartQueryRequest,
                                                     HttpServletRequest request) {
        long current = ChartQueryRequest.getCurrent();
        long size = ChartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> ChartPage = ChartService.page(new Page<>(current, size),
                getQueryWrapper(ChartQueryRequest));
        return ResultUtils.success(ChartPage);
    }

    /**
     * 智能分析(异步处理)
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<AiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);
        //限流
        redisLimitManage.doLimit("getChartByAi" + String.valueOf(loginUser.getId()));
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();
        //校验
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称为空");
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");
        //文件校验
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final Long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "上传文件不能超过1MB");
        //检验文件后缀
        final List<String> validSuffexList = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!validSuffexList.contains(suffix), ErrorCode.SYSTEM_ERROR, "文件后缀名不存在");

        /**
         * 分析模板
         * 分析需求
         * 分析目标
         * 原始数据
         * 最后csv结果
         **/
        Long modelId = 1659171950288818178L;

        //构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求").append("\n");
        String userGOal = goal;
        if (StringUtils.isNotBlank(userGOal)) {
            userGOal += goal + "," + chartType;
        }
        userInput.append(userGOal).append("\n");
        userInput.append("原始数据：").append("\n");


        //压缩后的数据
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append("数据：").append(csvData).append("\n");
        //插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        chart.setChartData(csvData);
        chart.setGoal(userGOal);
        //可以使用枚举
        chart.setStatus("wait");
        boolean save = ChartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "插入数据库失败");

        //todo 消息队列满了之后抛出异常
        CompletableFuture.runAsync(() -> {
            //先将图标任务状态设置’执行中‘，等执行完后在修改为”完成“，保存执行结果”，若为失败，则执行完修改为”失败”，记录失败信息
            Chart updateChat = new Chart();
            updateChat.setId(chart.getId());
            updateChat.setStatus("running");
            boolean b = ChartService.updateById(updateChat);
            if (!b) {
                handleChartUpdateError(chart.getId(), "更新状态执行中失败");
                return;
            }
            //调用Ai生成
            String answer = aiManage.doChat(modelId, userInput.toString());
            String[] splits = answer.split("【【【【【");
            if (splits.length < 3) {
                handleChartUpdateError(chart.getId(), "ai生成失败");

            }
            String genChart = splits[1].trim();
            String genResult = splits[2].trim();
            Chart updateChartResult = new Chart();
            //todo 定义枚举
            updateChartResult.setStatus("succeed");
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);
            boolean result = ChartService.updateById(updateChartResult);
            if (!result) {
                handleChartUpdateError(chart.getId(), "更新成功状态失败");
            }
        }, threadPoolExecutor);

        //返回结果
        AiResponse aiResponse = new AiResponse();
        aiResponse.setId(chart.getId());
        return ResultUtils.success(aiResponse);
    }

    /**
     * 智能分析(消息对列)
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/aysc/mq")
    public BaseResponse<AiResponse> genChartByAiMQ(@RequestPart("file") MultipartFile multipartFile,
                                                   GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        String chartType = genChartByAiRequest.getChartType();
        User loginUser = userService.getLoginUser(request);

        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();

        //校验
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称为空");
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空");

        //文件校验
        String originalFilename = multipartFile.getOriginalFilename();
        long size = multipartFile.getSize();
        final Long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "上传文件不能超过1MB");

        //检验文件后缀
        final List<String> validSuffexList = Arrays.asList("xlsx", "xls");
        String suffix = FileUtil.getSuffix(originalFilename);
        ThrowUtils.throwIf(!validSuffexList.contains(suffix), ErrorCode.SYSTEM_ERROR, "文件后缀名不存在");
        //限流
       redisLimitManage.doLimit("getChartByAi" + loginUser.getId());

        /**
         * 示例
         * 分析需求：
         * 分析网站用户的增长情况
         * 原始数据：
         * 日期,用户数
         * 1号,10
         * 2号,20
         * 3号,30
         **/

        StringBuilder userInput = new StringBuilder();

        userInput.append("分析需求").append("\n");
        String userGOal = goal;

        if (StringUtils.isNotBlank(chartType)) {
            userGOal += goal + "," + chartType;
        }
        //压缩后的数据
        String csvData=ExcelUtils.excelToCsv(multipartFile);
        userInput.append(userGOal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append("数据：").append(csvData).append("\n");

        Long modelId = CommonConstant.MODEL_ID;

        //插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setChartType(chartType);
        chart.setUserId(loginUser.getId());
        chart.setChartData(csvData);
        chart.setGoal(userGOal);
        //可以使用枚举
        chart.setStatus("wait");
        boolean save = ChartService.save(chart);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "插入数据库失败");

        //使用mq发送消息
        Long newChartId = chart.getId();
        biMessageProducer.send(String.valueOf(newChartId));

        //返回结果
        AiResponse aiResponse = new AiResponse();
        aiResponse.setId(newChartId);
        return ResultUtils.success(aiResponse);
    }

    /**
     * 封装异常处理
     *
     * @param chartId     图标id
     * @param execMessage 执行信息
     */
    private void handleChartUpdateError(Long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("Failed");
        updateChartResult.setExecMessage(execMessage);
        boolean b = ChartService.updateById(updateChartResult);
        if (!b) {
            log.error("更新图标状态失败失败" + chartId + "," + execMessage);
        }
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param ChartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    private BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest ChartQueryRequest,
                                                        HttpServletRequest request) {
        if (ChartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ChartQueryRequest.setUserId(loginUser.getId());
        long current = ChartQueryRequest.getCurrent();
        long size = ChartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = ChartService.page(new Page<>(current, size), getQueryWrapper(ChartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion


    /**
     * 编辑（管理员）
     * @param ChartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest ChartEditRequest, HttpServletRequest request) {
        if (ChartEditRequest == null || ChartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(ChartEditRequest, chart);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        long id = ChartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = ChartService.updateById(chart);
        return ResultUtils.success(result);
    }

    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        String goal = chartQueryRequest.getGoal();
        String name = chartQueryRequest.getName();
        String chartType = chartQueryRequest.getChartType();
        Long id = chartQueryRequest.getId();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id > 0, "id", "id");
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", "goal");
        queryWrapper.like(StringUtils.isNotBlank(name), "name", "name");
        queryWrapper.eq(StringUtils.isNotBlank(chartType), "chartType", "chartType");
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
}
